package qualomelhor.server;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import qualomelhor.database.*;
import java.util.List;
import java.util.Date;

public class EnviaEmail extends HttpServlet {

	private static final long serialVersionUID = 0;

	// Initialize a key set somehow:
    public void doGet(HttpServletRequest  req, HttpServletResponse res) throws IOException, ServletException {
    	doPost(req, res);
	}

	public void doPost(HttpServletRequest  req, HttpServletResponse res) throws IOException, ServletException {

		DAO d = new DAO();

		List<Email> listEmail = d.getListaEmailPendente(0, 8);
		res.getWriter().print("<HTML><BODY>");

		if (listEmail.size() == 0) {
			res.getWriter().print("Sem emails pendentes!");
		}
		
		for (int i = 0; i < listEmail.size(); i++) {
			EnviaContato.sendAppEmail(listEmail.get(i).getEmailDestinatarios(), listEmail.get(i).getAssunto(), listEmail.get(i).getBody(), listEmail.get(i).getContentType());

			Email e = d.getEmail(listEmail.get(i).getId());

			e.setEnviado(true);
			e.setDataEnvio(new Date());
			d.gravaNovoEmail(e);
			System.out.println("Email enviado!");
			res.getWriter().print("Email Enviado!<BR>");
		}
		res.getWriter().print("</HTML></BODY>");
	}
}